<template>

  <div class="app-container">
    <el-row :gutter="20">
      <!-- 工艺（左） -->
      <el-col :span="5" :xs="24">

        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span>工艺树</span>
            <el-button style="float: right; padding: 3px 0" type="text">+</el-button>
          </div>
          <el-tree
            :data="processTree"
            :props="defaultProps_processTree"
            :expand-on-click-node="false"
            ref="tree"
            default-expand-all
            :render-content="nodeRenderContent"
          />
        </el-card>
      </el-col>

      <!-- 详情（右） -->
      <el-col :span="19" :xs="24">
        <!-- 基本信息（右1） -->

        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;" >
          <div slot="header" class="clearfix">
            <span><b>基本信息</b></span>
            <el-tooltip content="显示 / 隐藏" placement="top" style="float: right; padding: 3px 0" >
              <el-switch
                v-model="fold_form_process_edit"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="false"
                inactive-value="true">
              </el-switch>
            </el-tooltip>
          </div>

          <el-collapse-transition>
            <el-row v-show="fold_form_process_edit == 'false'">
              <!-- 按钮：保存 -->
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button
                    type="success"
                    plain
                    icon="el-icon-check"
                    size="mini"
                    @click="update_process"
                    v-hasPermi="['mes:process:add']"
                  >保存</el-button>
                  <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="add_child_process"
                    v-hasPermi="['mes:process:add']"
                  >添加子零件</el-button>
                  <el-tooltip content="删除非根节点" placement="top">
                    <el-button
                      type="danger"
                      plain
                      icon="el-icon-delete"
                      size="mini"
                      @click="del_process"
                      v-hasPermi="['mes:process:add']"
                    >删除该零件</el-button>
                  </el-tooltip>
                </el-col>
              </el-row>

              <!-- 表单：工艺修改 -->
              <el-form ref="form_process_edit" :model="form_process_edit" :rules="rules_process" label-width="80px">
                <!-- 父ID -->
                <el-input v-model="form_process_edit.parentUuid" v-show="false" />
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="序号" prop="orderNum">
                      <el-input v-model="form_process_edit.orderNum" placeholder="请输入序号" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="版本号" prop="versionNum">
                      <el-input v-model="form_process_edit.versionNum" placeholder="请输入版本号" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="图纸号" prop="drawNum">
                      <el-input v-model="form_process_edit.drawNum" placeholder="请输入图纸号" />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="零件号" prop="partNum">
                      <el-input v-model="form_process_edit.partNum" placeholder="请输入零件号"/>
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="经办人" prop="fkItemUuid">
                      <el-input v-model="form_process_edit.fkAttentionUserId" v-show="false"  />
                      <el-input placeholder="请选择经办人" v-model="form_process_edit.selectedAttentionUser" class="input-with-select">
                        <el-button @click="showDialog_selectUser( form_process_edit )" slot="append" icon="el-icon-search" ></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="工艺编号" prop="docNum">
                      <el-input v-model="form_process_edit.docNum" placeholder="请输入编号" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="单据时间" prop="docDt">
                      <el-date-picker clearable size="small"
                                  v-model="form_process_edit.docDt"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="选择单据时间"
                                  :style="{width: '100%'}"
                      >
                      </el-date-picker>
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="数量" prop="processAmt">
                      <el-input v-model="form_process_edit.processAmt" placeholder="请输入数量" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="计量单位" prop="wmsDictMeasuringUnit">
                      <el-select v-model="form_process_edit.wmsDictMeasuringUnit"
                                 placeholder="请选择计量单位" :style="{width: '100%'}">
                        <el-option
                          v-for="dict in dict.type.wms_dict_measuring_unit"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="物料" prop="fkItemUuid">
                      <el-input v-model="form_process_edit.fkItemUuid" placeholder="请输入物料表ID" v-show="false"  />
                      <el-tooltip class="item" effect="dark" :content="form_process_edit.selectedItem_tooltip" placement="top">
                        <el-input placeholder="请输入内容" v-model="form_process_edit.selectedItem" class="input-with-select">
                          <el-button @click="showDialog_selectItem( form_process_edit )" slot="append" icon="el-icon-search" ></el-button>
                        </el-input>
                      </el-tooltip>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-row>
          </el-collapse-transition>
        </el-card>


        <!-- 物料（右2） -->
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span><b>物料清单</b></span>
            <el-tooltip content="显示 / 隐藏" placement="top" style="float: right; padding: 3px 0" >
              <el-switch
                v-model="fold_process_items"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="false"
                inactive-value="true">
              </el-switch>
            </el-tooltip>
          </div>

          <el-collapse-transition>
            <el-row v-show="fold_process_items == 'false'">

              <!-- 按钮：新增 -->
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="showDialog_item"
                    v-hasPermi="['mes:processItems:add']"
                  >添加物料</el-button>
                </el-col>
              </el-row>

              <!-- 列表：物料 -->
              <el-table v-loading="loading" :data="processItemList" row-key="processItemUuid">

                <el-table-column label="序号" align="center" prop="orderNum" />
                <el-table-column label="物料名称" align="center" prop="itemName" width="150"/>
                <el-table-column label="物料编码" align="center" prop="itemNum" width="160"/>
                <el-table-column label="规格" align="center" prop="itemSpecification" width="120"/>
                <el-table-column label="数量" align="center" prop="itemQty" />
                <el-table-column label="备件数量" align="center" prop="itemBakQty" />
                <el-table-column label="状态" align="center" prop="sysNormalDisable">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.sysNormalDisable"/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="update_item(scope.row)"
                      v-hasPermi="['mes:processItems:edit']"
                    >修改</el-button>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="del_item(scope.row)"
                      v-hasPermi="['mes:processItems:remove']"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="total_items>0"
                :total="total_items"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList_items"
              />
            </el-row>
          </el-collapse-transition>
        </el-card>


        <!-- 工序（右3） -->
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;" >

          <div slot="header" class="clearfix">
            <span><b>工序清单</b></span>
          </div>

          <!-- 按钮：新增工序 -->
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="showDialog_detail"
                v-hasPermi="['mes:process:add']"
              >添加工序</el-button>
            </el-col>

          </el-row>

          <!-- 列表：工序 -->
          <el-table v-loading="loading" :data="processDetailsList" row-key="processItemUuid" >

            <el-table-column label="序号" align="center" prop="orderNum" />
            <el-table-column label="工序号" align="center" prop="processCode" />
            <el-table-column label="工序符号" align="center" prop="mesDictProcessCode">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.mes_dict_process_code" :value="scope.row.mesDictProcessCode"/>
              </template>
            </el-table-column>
            <el-table-column label="工序类型" align="center" prop="mesDictProcessType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.mes_dict_process_type" :value="scope.row.mesDictProcessType"/>
              </template>
            </el-table-column>
            <el-table-column label="工序名称" align="center" prop="mesDictProcessName">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.mes_dict_process_name" :value="scope.row.mesDictProcessName"/>
              </template>
            </el-table-column>
            <el-table-column label="设备类型" align="center" prop="wmsDictDeviceType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.wms_dict_device_type" :value="scope.row.wmsDictDeviceType"/>
              </template>
            </el-table-column>

            <el-table-column label="工序内容" align="center" prop="processContent" />
            <el-table-column label="标准定额(分钟)" align="center" prop="quotaQtyMin" width="120"/>

            <el-table-column label="是否质检" align="center" prop="sysYesNoQc">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.sysYesNoQc"/>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="sysNormalDisable">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.sysNormalDisable"/>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="docNote" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="update_detail(scope.row)"
                  v-hasPermi="['mes:processDetails:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="del_detail(scope.row)"
                  v-hasPermi="['mes:processDetails:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total_details>0"
            :total="total_details"
            :page.sync="queryParams_details.pageNum"
            :limit.sync="queryParams_details.pageSize"
            @pagination="getList_details"
          />

        </el-card>

      </el-col>
    </el-row>

    <!--

      对话框（1）：添加工艺

      -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="dialog_title_process" :visible.sync="dialog_visible_process"
               width="800px" append-to-body :close-on-click-modal=false>
      <!-- 表单：工艺 -->
      <el-form ref="form_process" :model="form_process" :rules="rules_process" label-width="80px">

        <el-input v-model="form_process.processUuid" v-show="false" />
        <el-input v-model="form_process.parentUuid" v-show="false" />
      <el-row>
        <el-col :span="12">
        <el-form-item label="序号" prop="orderNum">
          <el-input v-model="form_process.orderNum" placeholder="请输入序号" :style="{width: '100%'}"/>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="版本号" prop="versionNum">
          <el-input v-model="form_process.versionNum" placeholder="请输入版本号" :style="{width: '100%'}"/>
        </el-form-item>
        </el-col>

        <el-col :span="12">
        <el-form-item label="图纸号" prop="drawNum">
          <el-input v-model="form_process.drawNum" placeholder="请输入图纸号" :style="{width: '100%'}"/>
        </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="零件号" prop="partNum">
            <el-input v-model="form_process.partNum" placeholder="请输入零件号"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
        <el-form-item label="物料" prop="fkItemUuid">
          <el-input v-model="form_process.fkItemUuid" v-show="false"  />
          <el-tooltip class="item" effect="dark" :content="form_process.selectedItem_tooltip" placement="top">
            <el-input placeholder="请选择" v-model="form_process.selectedItem" class="input-with-select" :style="{width: '100%'}">
              <el-button @click="showDialog_selectItem( form_process )" slot="append" icon="el-icon-search" ></el-button>
            </el-input>
          </el-tooltip>
        </el-form-item>
        </el-col>

        <el-col :span="12">
        <el-form-item label="工艺编号" prop="docNum">
          <el-input v-model="form_process.docNum" placeholder="请输入工艺编号" :style="{width: '100%'}"/>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="单据时间" prop="docDt">
          <el-date-picker clearable size="small"
                          v-model="form_process.docDt"
                          type="datetime"
                          placeholder="选择单据时间"
                          :style="{width: '100%'}">
          </el-date-picker>
        </el-form-item>
        </el-col>

          <el-col :span="12">
            <el-form-item label="数量" prop="processAmt">
              <el-input v-model="form_process.processAmt" placeholder="请输入数量" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="wmsDictMeasuringUnit">
              <el-select v-model="form_process.wmsDictMeasuringUnit" placeholder="请选择计量单位" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.wms_dict_measuring_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        <el-col :span="24">
        <el-form-item label="工艺员" prop="fkAttentionUserId">
          <el-input v-model="form_process.fkAttentionUserId" v-show="false"  />
          <el-input placeholder="请选择经办人" v-model="form_process.selectedAttentionUser" class="input-with-select" :style="{width: '100%'}">
            <el-button @click="showDialog_selectUser( form_process )" slot="append" icon="el-icon-search" ></el-button>
          </el-input>
        </el-form-item>
        </el-col>
      </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm_process">确 定</el-button>
        <el-button @click="dialog_hide_process">取 消</el-button>
      </div>
    </el-dialog>


    <!--

      对话框（2）：添加或修改工艺规程-物料

      -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="dialog_title_item"
               :visible.sync="dialog_visible_item" width="800px" append-to-body :close-on-click-modal=false>
      <el-form ref="form_item" :model="form_item" :rules="rules_item" label-width="100px">

        <el-input v-model="form_item.fkProcessUuid" v-show="false" />
      <el-row>
        <el-col :span="12">
        <el-form-item prop="orderNum">
          <span slot="label">
            排序序号
            <el-tooltip content="请设置显示顺序，默认值是 “1”，建议输入数字。" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-input v-model="form_item.orderNum" placeholder="请输入排序序号" :style="{width: '100%'}"/>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item prop="fkItemUuid">
          <span slot="label">
            物料
            <el-tooltip :content="form_item.selectedItem_tooltip" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-input v-model="form_item.fkItemUuid" v-show="false"  />
          <el-input placeholder="请选择物料" v-model="form_item.selectedItem" class="input-with-select" :style="{width: '100%'}">
            <el-button @click="showDialog_selectItem( form_item )" slot="append" icon="el-icon-search" ></el-button>
          </el-input>
        </el-form-item>
        </el-col>
      </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="数量" prop="itemQty">
          <el-input v-model="form_item.itemQty" placeholder="请输入数量" :style="{width: '100%'}"/>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="备件数量" prop="itemBakQty">
          <el-input v-model="form_item.itemBakQty" placeholder="请输入备件数量" :style="{width: '100%'}"/>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="状态">
          <el-radio-group v-model="form_item.sysNormalDisable" :style="{width: '100%'}">
            <el-radio
              v-for="dict in statusOptions_item"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
        <el-form-item label="备注" prop="docNote">
          <el-input v-model="form_item.docNote" autosize type="textarea" placeholder="请输入内容" :style="{width: '100%'}"/>
        </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button type="primary" @click="submitForm_item">确 定</el-button>
        <el-button @click="dialog_hide_item">取 消</el-button>
      </div>
    </el-dialog>



    <!--

      对话框（3）：添加或修改工艺规程-工序

      -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="dialog_title_detail" :visible.sync="dialog_visible_detail"
               width="750px" append-to-body :close-on-click-modal=false>
      <el-form ref="form_detail" :model="form_detail" :rules="rules_detail" label-width="100px">
<!--        工艺规程ID-->
        <el-input v-model="form_detail.fkProcessUuid" v-show="false" />
        <el-row>

          <el-col :span="12">
            <el-form-item label="排序序号" prop="orderNum">
              <el-input v-model="form_detail.orderNum" placeholder="请输入排序序号" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工序号" prop="processCode">
              <el-input v-model="form_detail.processCode" placeholder="请输入工序号" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工序类型" prop="mesDictProcessType">
              <el-select v-model="form_detail.mesDictProcessType" placeholder="请选择工序类型" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.mes_dict_process_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工序名称" prop="mesDictProcessName">
              <el-select v-model="form_detail.mesDictProcessName" placeholder="请选择工序名称" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.mes_dict_process_name"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工序符号" prop="mesDictProcessCode">
              <el-select v-model="form_detail.mesDictProcessCode" placeholder="请选择工序符号" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.mes_dict_process_code"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备类型" prop="wmsDictDeviceType">
              <el-select v-model="form_detail.wmsDictDeviceType" placeholder="请选择设备类型"  :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.wms_dict_device_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="工序内容">
              <editor v-model="form_detail.processContent" :min-height="192"/>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="是否质检">
              <el-radio-group v-model="form_detail.sysYesNoQc">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form_detail.sysNormalDisable">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>


          <el-col :span="12">

            <el-form-item prop="quotaQtyMin">
               <span slot="label">
                标准定额
                  <el-tooltip content="标准定额单位(分钟)" placement="top">
                    <i class="el-icon-question"></i>
                 </el-tooltip>
              </span>
              <el-input v-model="form_detail.quotaQtyMin" placeholder="请输入标准定额" :style="{width: '100%'}">
                <template slot="append">分钟</template>
              </el-input>
            </el-form-item>
          </el-col>


          <el-col :span="24">
        <el-form-item label="备注" prop="docNote">
          <el-input v-model="form_detail.docNote" autosize type="textarea" placeholder="请输入内容" :style="{width: '100%'}"/>
        </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm_detail">确 定</el-button>
        <el-button @click="dialog_hide_detail">取 消</el-button>
      </div>
    </el-dialog>

    <select-user ref="component_selectUser" @ok="selectUser_done" />
    <select-item ref="component_selectItem" @ok="selectItem_done" />

  </div>
</template>

<script>
import { getProcess, delProcess, addProcess, updateProcess, treeSelect } from "@/api/mes/process";
import { listItems, getItems, delItems, addItems, updateItems } from "@/api/mes/processItems";
import { listProcessDetails, getProcessDetails, delProcessDetails, addProcessDetails, updateProcessDetails } from "@/api/mes/processDetails";
import selectUser from "../../comn/userGroup/selectUser";
import {getInfo} from "@/api/login";
import selectItem from "../../wms/wmsItems/selectItem";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { parseTime } from '@/utils/ruoyi'
import {newDocNum} from "@/api/oa/docNum";
export default {
  dicts:['sys_normal_disable', 'mes_dict_process_type', 'mes_dict_process_name',
    'mes_dict_process_code', 'sys_yes_no','wms_dict_measuring_unit','wms_dict_device_type'],
  name: "Process",
  components: { Treeselect, selectUser, selectItem },
  data() {
    return {
      currentForm: null, // 当前表单，用来标识打开《选择用户》、《选择物料》窗口的表单
      fold_form_process_edit: 'false',
      fold_process_items: 'false',
      rootProcessUuid: '', // 工艺树根节点
      currProcessUuid: '', // 当前工艺ID
      dialog_title_process: '', // 对话框标题：工序
      dialog_title_item: "", // 弹出层标题：物料
      dialog_title_detail: '', // 对话框标题：工序明细
      dialog_visible_process: false, // 对话框是否可见：工序
      dialog_visible_item: false,
      dialog_visible_detail: false,

      processTree: undefined, // 工艺树
      loading: true, // 遮罩层
      showSearch: true, // 显示搜索条件

      total: 0, // 总条数
      total_items: 0, // 总条数
      total_details: 0, // 总条数

      processList: [], // 工艺规程表格数据
      processItemList: [],
      processDetailsList: [],
      title: "", // 弹出层标题
      statusOptions_item: [], // 状态选项：物料

      open: false, // 是否显示弹出层
      dialog_selectItem: { // 对话框：选择物料
        visible: false,
        title: "请选择物料",
        total: 0,
        itemList: [],
        queryParams:{
          itemName: null,
        }
      },
      // 查询参数
      queryParams: {
        ancestors: '',
        parentUuid: null,
        versionNum: null,
        drawNum: null,
        fkItemUuid: null,

        docNum: null,
        docDt: null,
        fkAttentionUserId: null,
      },
      // 查询参数
      queryParams_items: {
      },
      // 查询参数
      queryParams_details: {
      },
      // 表单参数
      form: {},
      form_item: {
        selectedItem: ''
      },
      form_detail: {},
      form_process: {
        parentUuid: null,
      },
      form_process_edit: {
        parentUuid: null,
      },
      defaultProps_processTree: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        parentUuid: [
          { required: true, message: "父ID不能为空", trigger: "blur" }
        ],
        versionNum: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ],
        fkItemUuid: [
          { required: true, message: "物料表ID不能为空", trigger: "blur" }
        ],

        docNum: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
        docDt: [
          { required: true, message: "单据时间不能为空", trigger: "blur" }
        ],
        fkAttentionUserId: [
          { required: true, message: "经办人ID不能为空", trigger: "blur" }
        ],
      },
      rules_detail:{
        mesDictProcessName: [
          { required: true, message: "请选择工序名称", trigger: "change" }
        ],
        mesDictProcessType: [
          { required: true, message: "请选择工序类型", trigger: "change" }
        ],
      },
      rules_process: {
        versionNum: [
          { required: true, message: "请选择工序符号", trigger: "change" }
        ],
        drawNum: [
          { required: true, message: "请选择工序名称", trigger: "change" }
        ],
        partNum: [
          { required: true, message: "请输入零件号", trigger: "change" }
        ],
        fkItemUuid: [
          { required: true, message: "请选择工序类型", trigger: "change" }
        ],
        docNum: [
          { required: true, message: "请选择工序符号", trigger: "change" }
        ],
        docDt: [
          { required: true, message: "请选择工序名称", trigger: "change" }
        ],
        fkAttentionUserId: [
          { required: true, message: "请选择工序类型", trigger: "change" }
        ],

      },
      rules_item:{
        fkProcessUuid: [
          { required: true, message: "工艺规程ID不能为空", trigger: "blur" }
        ],
        fkItemUuid: [
          { required: true, message: "请选择物料", trigger: "change" }
        ],
        itemQty: [
          { required: true, message: "请输入数量", trigger: "change" }
        ],
        itemBakQty: [
          { required: true, message: "请输入备件数量", trigger: "change" }
        ],
        sysNormalDisable: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    // 接收参数
    const rootProcessUuid = this.$route.params && this.$route.params.processUuid;
    if(rootProcessUuid){
      this.rootProcessUuid = rootProcessUuid
      this.currProcessUuid = rootProcessUuid
      this.queryParams.ancestors = rootProcessUuid
    }

    // 字典
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions_item = response.data;
    });

    this.getList_process(); // 工艺
    // this.getList_items(); // 物料
    // this.getList_details(); // 工序明细

    this.nodeClick_process({id: this.currProcessUuid })

    getInfo().then(response => {
      this.currUser = response.user
    });

  },
  methods: {

    // 左 - 1

    /** 树：工艺 */
    getList_process() {
      this.queryParams.orderNum = true
      treeSelect(this.queryParams).then(response => {
        this.processTree = response.data
      });
    },

    /** 树节点单击事件 */
    nodeClick_process(data) {
      this.loading = true;
      this.currProcessUuid = data.id

      getProcess(data.id).then(response => {
        this.loading = false;
        this.form_process.parentUuid = response.data.processUuid
        console.log(response)
        this.form_process_edit = response.data
        this.form_process_edit.selectedItem = `${response.data.itemName}（物料编码：${response.data.itemNum}）`
        this.form_process_edit.selectedItem_tooltip = `物料唯一标识：${response.data.itemUuid}`
        this.form_process_edit.selectedAttentionUser = `${response.data.attentionUserName}（用户 ID：${response.data.fkAttentionUserId}）`
      });

      this.getList_items()
      this.getList_details()

    },

    // 右 - 1

    /** 修改：工艺基本信息 */
    update_process(){
      this.$modal.msgSuccess("修改工艺基本信息 ...");

      this.$refs["form_process_edit"].validate(valid => {
        if (valid) {
          console.log( this.form_process_edit )
          updateProcess(this.form_process_edit).then(response => {
            this.$modal.msgSuccess("修改成功!");
            this.getList_process();
            this.nodeClick_process({id: this.currProcessUuid })
          });
        }
      });
    },

    /** 添加子节点 */
    add_child_process(){
      newDocNum({preCode: 'PRO-', len: 12}).then(response => {
        this.form_process.docNum = response.msg
      })
      this.showDialog_process()
    },

    /** 删除当前节点 */
    del_process(){
      this.$modal.msgSuccess("删除当前节点 ...");
      if( this.currProcessUuid == this.rootProcessUuid ){
        this.$alert('该页面不能删除根节点', '禁止删除', {
          confirmButtonText: '确定',
          type: 'error',
          callback: action => {}
        });
        return
      }
      console.log( this.form_process_edit)
      const ids = this.currProcessUuid || this.ids;
      this.$modal.confirm(`是否确认删除 ${this.form_process_edit.selectedItem}的工艺规程？`)
        .then(function() {
        return delProcess(ids);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList_process()
        this.nodeClick_process({id: this.rootProcessUuid })
      }).catch(() => {});

    },

    // 右 - 2

    /** 列表：物料 */
    getList_items(){
      this.loading = true;
      this.queryParams_items.fkProcessUuid = this.currProcessUuid
      listItems(this.queryParams_items).then(response => {
        this.processItemList = response.rows;
        this.total_items = response.total;
        this.loading = false;
      });
    },

    /** 修改 - 物料 */
    update_item(row) {
      console.log( row )
      this.resetForm_item();
      const processItemUuid = row.processItemUuid || this.ids
      getItems(processItemUuid).then(response => {
        console.log( response )
        this.form_item = response.data;
        this.form_item.selectedItem = `${response.data.itemName}（编号：${response.data.itemNum}）` ;
        this.dialog_visible_item = true;
        this.dialog_title_item = "修改工艺规程-工序明细";
      });
    },

    /** 删除按钮操作 */
    del_item(row) {
      console.log(row)
      const ids = row.processItemUuid || this.ids;
      this.$modal.confirm(`是否确认删除序号为 ${row.orderNum} 的物料？`,'删除确认').then(function() {
        return delItems(ids);
      }).then(() => {
        this.getList_items();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },


    // 右 - 3

    /** 列表：明细 */
    getList_details(){
      this.loading = true;
      this.queryParams_details.fkProcessUuid = this.currProcessUuid
      listProcessDetails(this.queryParams_details).then(response => {
        this.processDetailsList = response.rows;
        this.total_details = response.total;
        this.loading = false;
      });
    },

    /** 修改 - 明细 */
    update_detail(row) {
      this.resetForm_detail();
      const processDetailUuid = row.processDetailUuid || this.ids
      getProcessDetails(processDetailUuid).then(response => {
        this.form_detail = response.data;
        this.dialog_visible_detail = true;
        this.dialog_title_detail = "修改工艺规程-工序明细";
      });
    },

    /** 删除按钮操作 */
    del_detail(row) {
      console.log(row)
      const ids = row.processDetailUuid || this.ids;
      this.$modal.confirm(`是否确认删除序号为 ${row.orderNum} 的工序？`,'删除确认').then(function() {
        return delProcessDetails(ids);
      }).then(() => {
        this.getList_details();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },


    // 对话框 - 1

    /** 新增按钮操作 */
    showDialog_process(processUuid) {
      this.resetForm_process();
      // this.getList_process();
      if ( processUuid != null) {
        this.form_process.parentUuid = processUuid;
      } else {
        this.form_process.parentUuid = this.currProcessUuid ;
      }
      this.dialog_visible_process = true;
      this.dialog_title_process = "新增工艺节点";
      this.form_process.selectedItem_tooltip = `请选择物料`
    },

    // 对话框：隐藏 - 选择物料
    dialog_hide_process() {
      this.dialog_visible_process = false;
    },

    // 表单重置：工艺
    resetForm_process() {
      this.form_process = {
        processUuid: null,
        parentUuid: null,
        versionNum: null,
        drawNum: null,
        fkItemUuid: null,
        selectedAttentionUser:`${this.currUser.nickName}（${this.currUser.userId}）`,
        docNum: null,
        docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
        fkAttentionUserId: this.currUser.userId,
      };
      this.resetForm("form_process");
    },

    /** 提交按钮 */
    submitForm_process() {
      console.log('submitForm_process')
      this.$refs["form_process"].validate(valid => {
        if (valid) {
          if (this.form_process.processUuid != null) {
            updateProcess(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList_process();
            });
          } else {
            addProcess(this.form_process).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialog_visible_process = false;
              this.getList_process();
            });
          }
        }
      });
    },

    // 对话框 - 2

    // 表单重置：工艺
    resetForm_item() {
      this.form_item = {
        fkProcessUuid: this.currProcessUuid,
        sysNormalDisable: '0',
        orderNum: null,
        selectedItem_tooltip: '请选择物料',
        selectedItem: null,
        fkItemUuid: null,
        mesDictProcessName: null,
        itemQty: null,
        itemBakQty: '0',
      };
      this.resetForm("form_item");
    },

    /** 对话框：显示 = 物料明细 */
    showDialog_item(){
      this.resetForm_item()
      // this.$modal.msgSuccess("对话框：显示 = 物料明细 showDialog_item()");
      // this.form_item.fkProcessUuid = this.currProcessUuid
      // this.form_item.sysNormalDisable = '0'
      // this.form_item.orderNum = '1'
      this.dialog_visible_item = true
      this.dialog_title_item = '新增工艺物料'
      // this.form_item.selectedItem_tooltip = '请选择物料'
    },

    dialog_hide_item(){
      this.dialog_visible_item = false
      this.$refs["form_item"].resetFields()
    },

    /** 提交按钮 */
    submitForm_item() {
      this.$refs["form_item"].validate(valid => {
        if (valid) {
          if (this.form_item.processItemUuid != null) {
            updateItems(this.form_item).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialog_visible_item = false;
              this.getList_items();
            });
          } else {
            addItems(this.form_item).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialog_visible_item = false;
              this.getList_items();
            });
          }
        }
      });
    },


    // 对话框 - 3


    // 表单重置：工艺
    resetForm_detail() {
      this.form_detail = {
        fkProcessUuid: this.currProcessUuid,
        orderNum: '1',
        mesDictProcessType: null,
        mesDictProcessName: null,
        mesDictProcessCode: null,
        wmsDictDeviceType: null,
        processContent: null,
        sysYesNoCopy: "Y",
        sysYesNoQc: "Y",
        sysNormalDisable: "0",
        docNote: null
      };
      this.resetForm("form_detail");
    },

    /** 对话框：显示 = 工序明细 */
    showDialog_detail(){
      this.resetForm_detail()
      this.$modal.msgSuccess("对话框：显示 = 工序明细 showDialog_detail()");
      this.dialog_visible_detail = true
    },


    dialog_hide_detail(){
      this.dialog_visible_detail = false
    },

    /** 提交按钮 */
    submitForm_detail() {
      this.$refs["form_detail"].validate(valid => {
        if (valid) {
          if (this.form_detail.processDetailUuid != null) {
            updateProcessDetails(this.form_detail).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialog_visible_detail = false;
              this.getList_details();
            });
          } else {
            addProcessDetails(this.form_detail).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialog_visible_detail = false;
              this.getList_details();
            });
          }
        }
      });
    },



    // 构建树

    /** 转换工艺规程数据结构 */
    // normalizer(node) {
      // console.log(node)
      // if (node.children && !node.children.length) {
      //   delete node.children;
      // }
      // return {
      //   id: node.processUuid,
      //   label: node.fkItemUuid,
      //   children: node.children
      // };
    // },

    /** 构建树节点 */
    nodeRenderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
            <span>
              <el-button size="mini" type="text" on-click={ () => this.nodeClick_process(data) }>{node.label}</el-button>
              <el-button size="mini" type="text" on-click={ () => this.showDialog_process(data.id) }> + </el-button>
              <el-button size="mini" type="text" on-click={ () => this.remove(node, data) }> - </el-button>
            </span>
          </span>);
    },

    // 取消按钮
    // cancel() {
    //   this.open = false;
    //   this.resetForm_process();
    // },


    /** 重置按钮操作 */
    // resetQuery() {
    //   this.resetForm("queryForm");
    //   this.handleQuery();
    // },

    /** 多选框：选中数据有变化 */
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.taskUuid)
    //   this.single = selection.length!==1
    //   this.multiple = !selection.length
    // },

    // 组件 - 选择物料

    // 对话框：显示 - 选择物料
    showDialog_selectItem( form ) {
      if( !form ) console.log('form is null!')
      this.currentForm = form
      this.$refs.component_selectItem.dialog_show_selectItem();
    },

    // 完成：选择物料
    selectItem_done(item) {
      this.currentForm.fkItemUuid = item.itemUuid
      this.currentForm.selectedItem = `${item.itemName}（物料编码：${item.itemNum}）`
      // this.currentForm.selectedItem_tooltip = `物料的唯一标识：${item.itemUuid}`
    },



    // 组件 - 选择用户

    /** 打开授权用户表弹窗 */
    showDialog_selectUser( form ) {
      this.currentForm = form
      this.$refs.component_selectUser.userGroup='technologist'
      this.$refs.component_selectUser.show();
    },

    /** 选择用户完成 */
    selectUser_done(user) {
      this.currentForm.fkAttentionUserId = user.userId
      this.currentForm.selectedAttentionUser = `${user.nickName}（用户名：${user.userName}，ID：${user.userId}）`
    },


    /** 修改按钮操作 */
    // update_process(row) {
    //   this.resetForm_process();
    //   // this.getList_process();
    //   if (row != null) {
    //     this.form.parentUuid = row.processUuid;
    //   }
    //   getProcess(row.processUuid).then(response => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改工艺规程";
    //     this.form.selectedItem = `${this.form.itemName}（物料编码：${this.form.itemNum}）`
    //     this.form.selectedItem_tooltip = `物料的唯一标识：${this.form.itemUuid}`
    //   });
    // },






    /** 删除按钮操作 */
    // handleDelete(row) {
    // },


    /**
     *  ------------- 选择物料 -------------
     * */


    /** 读取列表：物料 */
    // getList_items() {
    //   this.loading = true;
    //   listWmsItems(this.dialog_selectItem.queryParams).then(response => {
    //     console.log( response )
    //     this.dialog_selectItem.itemList = response.rows;
    //     this.dialog_selectItem.total = response.total;
    //     this.loading = false;
    //   });
    // },

    // 对话框：隐藏 - 选择物料
    // dialog_hide_selectItem() {
    //   this.dialog_selectItem.visible = false;
    // },




  }
};
</script>
